package mobilizator.app;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class ParserXML {
	float temperature;
	Boolean summary;

	public ParserXML(String str) {

		Document doc = XMLfromString(str);
		NodeList nodes = doc.getElementsByTagName("temp_c");
		Element element = (Element)nodes.item(0);
		temperature = Float.parseFloat(element.getAttribute("data"));
		nodes = doc.getElementsByTagName("icon");
		element = (Element)nodes.item(0);
		String string = element.getAttribute("data");
		
		if(string.equals("/ig/images/weather/icy.gif") || string.equals("/ig/images/weather/dusty.gif") || string.equals("/ig/images/weather/hazy.gif") 
				||string.equals("/ig/images/weather/smoke.gif") || string.equals("/ig/images/weather/foggy.gif") ||string.equals("/ig/images/weather/fog.gif") 
				|| string.equals("/ig/images/weather/cloudy.gif") ||string.equals("/ig/images/weather/mostly_cloudy.gif") ||string.equals("/ig/images/weather/partly_cloudy.gif") 
				|| string.equals("/ig/images/weather/mostly_sunny.gif") ||string.equals("/ig/images/weather/sunny.gif"))
			summary = false;
		else
			summary = true;
		
	}
	
	public float getTemp() {
		return temperature;
	}
	
	public boolean isRainy() {
		return summary;
	}

	public static String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return getTextFromNode(n.item(0));
	}

	public final static String getTextFromNode(Node elem) {
		Node kid;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (kid = elem.getFirstChild(); kid != null; kid = kid
						.getNextSibling()) {
					if (kid.getNodeType() == Node.TEXT_NODE) {
						return kid.getNodeValue();
					}
				}
			}
		}
		return "";
	}

	public Document XMLfromString(String string) {

		Document document = null;
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		try {
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			InputSource iSource = new InputSource();
			iSource.setCharacterStream(new StringReader(string));
			document = docBuilder.parse(iSource);
		} catch (ParserConfigurationException e) {
			System.out.println("XML parse error: " + e.getMessage());
			return null;
		} catch (SAXException e) {
			System.out.println("Wrong XML file structure: " + e.getMessage());
			return null;
		} catch (IOException e) {
			System.out.println("I/O exeption: " + e.getMessage());
			return null;
		}
		return document;

	}
}
